<?php

namespace Services\WxGongZhong;

use Common\Util\BaseData;
use Services\BaseService;
use Services\Log\LogService;
use Services\Request\WxGongZhongRequest;
use Services\User\UserService;
use Services\WxGongZhong\Exceptions\WxGongZhongException;

class WxGongZhongService extends BaseService
{
    /** @var WxGongZhongRequest */
    private $request;

    private $logTag = '公众号服务';

    public function __construct($config = [])
    {
        $this->init($config);
    }


    public function init($config = [])
    {
        $this->request = new WxGongZhongRequest($config);
    }

    /**
     * 发送访问消息提醒
     * @param $userId
     * @param $viewNumber
     * @return void
     */
    public function sendViewMessage($userId, $viewNumber = 1)
    {
        $status = false;
        try {
            $appSetting = BaseData::getAppSetting();
            $config = [
                'appid' => arr_get($appSetting,'wechat_appid'),
                'secret' => arr_get($appSetting,'wechat_appsecret'),
            ];
            $this->init($config);
            $userInfo = (new UserService())->getUserById($userId);
            if (empty($userInfo)) {
                throw new WxGongZhongException('用户不存在');
            }
            $requestData = [
                'touser' => arr_get($userInfo, 'user_openid'),
                'template_id' => 'NHhKuayLQlV2sDBb2uwIwcrNzNeu5GeXR-puCSp2vA8',
                'url' => $appSetting['beiyong_app_domain'] . '/h5app/pages/track/track',
                'data' => [
                    'thing1' => [
                        'value' => '有客来访',
                        'color' => "#fc0101"
                    ],
                    'character_string14' => [
                        'value' => $viewNumber,
                        'color' => "#173177"
                    ]
                ],

            ];
            $result = $this->request->sendTemplateMessage($requestData);
            $errcode = arr_get($result, 'errcode');
            $status = $errcode == 0;
            if($status){
                (new UserService())->updateUserMessageTip($userId);
            }
        } catch (WxGongZhongException $e) {
            LogService::writeWithDb(format_exception($e), '访客提醒异常', $this->logTag);
        }
        return $status;
    }
}
